$(document).ready(function(){
	var pluginUserChatMaxId = 0;
	var reqId = 0;
	function pluginUserChatLoadData(){
		$.getJSON(pluginUserChatFullLink+"data.php?start="+pluginUserChatMaxId+"&req="+reqId, function(data){
			reqId++;
			$.each(data, function(key, value){
				$(".pluginUserChat").prepend("<div class=\"item\" style=\"display:none;\"><b>"+value.username+":</b> "+value.text+"</div>");
				if(parseInt(value.id) > pluginUserChatMaxId){ pluginUserChatMaxId = value.id; }
				if($(".pluginUserChat .item").length > 20){
					$(".pluginUserChat .item:last").remove();
				}
			});
			$(".pluginUserChat .item:hidden").slideDown("fast");
			setTimeout(pluginUserChatLoadData, 2500);
		});
	}
	
	$('#pluginUserChatText').keyup(function(e){
		if(e.keyCode == 13){
			pluginUserChatSend();
		}
		$("#pluginUserChatButton").attr("value", "Send ("+$("#pluginUserChatText").val().length+")");
	});
	
	function pluginUserChatSend(){
		$("#pluginUserChatButton").attr("disabled", "disabled");
		$("#pluginUserChatText").attr("disabled", "disabled");
		$.ajax({
			type: "post",
			url: pluginUserChatFullLink+"data.php",
			data: "text="+$("#pluginUserChatText").val(),
			dataType: "json",
			success: function(data){
				if(data.stats == "login"){
					alert("You have to login in order to use this chat.");
				}else if(data.stats == "good"){
				}else if(data.stats == "toolong"){
					alert("Message you have entered was too long. (maximum char limit is "+data.max+")");
				}else if(data.stats == "tooshort"){
					alert("Message you have entered was too short. (minimum char count is "+data.min+")");
				}
				
				$("#pluginUserChatButton").attr("disabled", "");
				$("#pluginUserChatText").attr("disabled", "");
				$("#pluginUserChatText").val("");
				$("#pluginUserChatButton").attr("value", "Send ("+$("#pluginUserChatText").val().length+")");
				$("#pluginUserChatText").focus();
			}
		});
	}
	
	$("#pluginUserChatButton").click(function(){
		pluginUserChatSend();
	});
	
	pluginUserChatLoadData();
});